const dao = require('../dao').type()
const Neo4j = require('node-neo4j')
const getRes = require('../util').getRes
const { 
  getNeo4jFromMongoDB, 
  getRelationTypesByNeo4j, 
  getNodeTypesByNeo4j 
} = require('../dao').graph()

// 获取节点类型
const getNodeTypes = async username => {
  const res = await dao.getNodeTypesByMongoDB(username)
  return getRes('success', res, '请求成功')
}
// 获取节点类型v2
const getNodeTypesV2 = async username => {
  const neo = await getNeo4jFromMongoDB(username)
  const res = await getNodeTypesByNeo4j(new Neo4j(neo.url))
  return getRes('success', res, '请求成功')
}

// 新增节点类型
const addNodeType = async (username, newType) => {
  // 类型查重
  const check = await dao.isExistNodeType(username, newType)
  if (check === true) {
    return getRes('fail', {}, '该节点类型已存在')
  }
  await dao.addNodeType(username, newType)
  return getRes('success', {}, '节点类型添加成功')
}

// 根据类型获取节点数量
const getNodeCount = async (username, nodeType) => {
  // 获取知识图谱连接器
  const neo = await getNeo4jFromMongoDB(username)
  // 查询节点数量
  const res = await dao.getNodeCountByNodeType(neo, nodeType)
  return getRes('success', res, '查询成功')
}

// 获取关系类型
const getRelationTypes = async username => {
  const res = await dao.getRelationTypesByMongoDB(username)
  return getRes('success', res, '请求成功')
}
// 获取关系类型 v2
const getRelationTypesV2 = async username => {
  const neo = await getNeo4jFromMongoDB(username)
  const res = await getRelationTypesByNeo4j(new Neo4j(neo.url))
  return getRes('success', res, '请求成功')
}

// 新增关系类型
const addRelationType = async (username, newType) => {
  // 类型查重
  const check = await dao.isExistRelationType(username, newType)
  if (check) {
    return getRes('fail', {}, '该关系类型已存在')
  }
  await dao.addRelationType(username, newType)
  return getRes('success', {}, '关系类型添加成功')
}

// 根据类型获取关系数量
const getRelationCount = async (username, relationType) => {
  // 获取知识图谱连接器
  const neo = await getNeo4jFromMongoDB(username)
  // 查询数量
  const res = await dao.getRelationCountByNodeType(neo, relationType)
  return getRes('success', res, '查询成功')
}

module.exports = {
  getNodeTypes,
  getNodeTypesV2,
  getRelationTypes,
  getRelationTypesV2,
  addNodeType,
  addRelationType,
  getNodeCount,
  getRelationCount
}